package xyz.zq.cloud.admin.controller;


import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.zq.cloud.admin.service.MenuService;
import xyz.zq.cloud.bs.api.dto.MenuTree;
import xyz.zq.cloud.bs.api.vo.MenuVO;
import xyz.zq.cloud.bs.api.vo.TreeUtil;
import xyz.zq.cloud.common.core.constant.CommonConstants;
import xyz.zq.cloud.common.core.util.R;
import xyz.zq.cloud.common.security.util.SecurityUtils;

import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author hzq
 * @since 2020-05-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/menu")
public class MenuController {

    private final MenuService menuService;

    /**
     * 返回当前用户的树形菜单集合
     *
     * @return 当前用户的树形菜单
     */
    @GetMapping
    public R getUserMenu() {
        // 获取符合条件的菜单
        Set<MenuVO> all = new HashSet<>();
        SecurityUtils.getRoles()
                .forEach(roleId -> all.addAll(menuService.getMenuByRoleId(roleId)));
        List<MenuTree> menuTreeList = all.stream()
                .filter(menuVo -> (0 == menuVo.getType() && 0 == menuVo.getBelong()))
                .map(MenuTree::new)
                .sorted(Comparator.comparingInt(MenuTree::getSort))
                .collect(Collectors.toList());
        return R.ok(TreeUtil.buildByLoop(menuTreeList, -1));
    }
}

